
#include <QString>
#include <QDebug>

#include "libpload.h"
#include "PLoadLib.h"

LibPload::LibPload()
{
}

int LibPload::open(QString portname, int baud)
{
    return ::popenport(portname.toLatin1().data(), baud);
}

int LibPload::close()
{
    return ::pcloseport();
}

int LibPload::find(QString portname)
{
    return ::findprop(portname.toLatin1().data());
}

int LibPload::upload(QString filename, int operation)
{
    return ::pload(filename.toLatin1().data(), operation);
}

int LibPload::load(QString filename, int operation, int fileid)
{
    int rc = 0;
    if(fileid == -1) {
        qDebug("Error port must be opened.\n");
        return 1;
    }
    serial_sethandle(fileid);
    if(pload(filename.toLatin1().data(), operation) != 0) {
        qDebug() << filename << "Load failed\n";
        rc = 2;
    }
    return rc;
}

int LibPload::load(QString filename, int operation, QString portname, int baud)
{
    int rc = 0;
    if((rc = popenport(portname.toLatin1().data(), baud))) {
        if(rc == PLOAD_STATUS_OPEN_FAILED)
            qDebug() << "Error opening port" << portname << "at" << baud << "bps";
        else
            qDebug() << "Propeller not found on" << portname;
        rc = 1;
    }
    else if((rc |= pload(filename.toLatin1().data(), operation))) {
        qDebug() << filename << "Load failed\n";
        rc = 2;
    }
    pcloseport();
    return rc;
}

